﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace WindowsFormsApplication1.WhoRequests
{
    public class WhoRequestManager
    {
        private List<WhoRequest> pendingRequests = new List<WhoRequest>();

        public void sendWhoRequest(int characterId, ServerSocketData requestingServer)
        {
            WhoRequest request = new WhoRequest(requestingServer, characterId);
        }
        public void sendWhoRequest(WhoRequest request)
        {
            lock (pendingRequests)
            {
                pendingRequests.Add(request);
            }
            request.sendRequests();
        }
        public void timeoutRequest(WhoRequest request)
        {
            lock (pendingRequests)
            {
                if (pendingRequests.Contains(request))
                {
                    pendingRequests.Remove(request);
                    request.timeoutRequest();
                }
            }
        }

        public void processWhoResult(ServerSocketData fromServer, int characterId, string xmlMessage)
        {
            //Get list of friend IDs we're going to query from the other world servers
            List<string> charactersOnline = new List<string>();

            if (xmlMessage != "")
            {
                StringReader sr = new StringReader(xmlMessage);
                XmlTextReader xmlReader = new XmlTextReader(sr);
                while (xmlReader.Read())
                {
                    if (xmlReader.Name == "characteronline" && xmlReader.IsStartElement())
                        charactersOnline.Add(xmlReader.ReadString());
                }
            }
            lock (pendingRequests)
            {
                foreach (WhoRequest request in pendingRequests)
                {
                    if (request.characterId == characterId)
                    {
                        request.processResult(fromServer, charactersOnline);
                        break;
                    }
                }
            }
        }
        public void completeRequest(WhoRequest request)
        {
            lock (pendingRequests)
            {
                if (pendingRequests.Contains(request))
                {
                    pendingRequests.Remove(request);
                    request.completeRequest();
                }
            }
        }
    }
}
